﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Globalization;

namespace Model
{
    public class ClTripleDES
    {
        private TripleDES tdes = TripleDES.Create();

        public ClTripleDES()
        {
            string sKey = "021364589753219864862159";
            string sIV = "59575153";

            if (sKey.Length > 24)
                sKey = sKey.Substring(0, 24);
            else
            {
                while (sKey.Length < 24)
                    sKey += ".";
            }

            if (sIV.Length > 8)
                sIV = sIV.Substring(0, 8);
            else
            {
                while (sIV.Length < 8)
                    sIV += ".";
            }

            byte[] key = Encoding.ASCII.GetBytes(sKey);
            byte[] iv = Encoding.ASCII.GetBytes(sIV);

            this.tdes.IV = iv;
            this.tdes.Key = key;
            this.tdes.Mode = CipherMode.CBC;
            this.tdes.Padding = PaddingMode.Zeros;
        }

        public string Encrypte(string str)
        {
            ICryptoTransform ict = this.tdes.CreateEncryptor();
            byte[] data = Encoding.Unicode.GetBytes(str);
            byte[] enc = ict.TransformFinalBlock(data, 0, data.Length);
            return BitConverter.ToString(enc).Replace("-", "");
        }

        public string Decrypte(string str)
        {
            try
            {
                int index = 0;
                byte[] data = new byte[str.Length / 2];
                for (index = 0; index < data.Length; index++)
                    data[index] = byte.Parse(str.Substring(index * 2, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);

                ICryptoTransform ict = this.tdes.CreateDecryptor();
                byte[] dec = ict.TransformFinalBlock(data, 0, data.Length);
                return Encoding.Unicode.GetString(dec).Replace("\0", "");
            }
            catch
            {
                return "";
            }
        }
    }
}
